package com.example.demoredis.controller;


import com.example.democommon.tools.Result;
import com.example.service.SysUserService;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * <p>
 * test
 * </p>
 *
 * @author ross zhang
 * @version 1.0
 * @PackageName demo-one
 * @Package com.example.demoredis.controller
 * @since 2022/4/15 10:19
 */
@RestController
public class TestController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/addAuthor")
    public Result<?> addAuthor(){
        //获取系统处理器个数，作为线程池数量
        int nThreads = Runtime.getRuntime().availableProcessors();
        System.out.println("获取系统处理器个数:"+nThreads);
        //定义线程
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("Test-%d").build();
        //Common Thread Pool,如果5分钟内不活动则终止任务
        ThreadPoolExecutor exec = new ThreadPoolExecutor(nThreads, 20,
                10L, TimeUnit.MINUTES,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        //允许核心线程销毁
//        exec.allowCoreThreadTimeOut(true);


        for (int i = 0; i < nThreads; i++) {
            int finalI = i;
            exec.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        sysUserService.list();
                        System.out.println("线程"+Thread.currentThread().getName()+"执行了一行数据"+finalI);
                    } catch (Exception e) {
                        System.out.println("线程销毁：" + e.getMessage());
                    }
                }
            });
        }

        //关闭线程池
        exec.shutdown();

        while (true) {
            /**
             * 如果所有任务在关闭后都已完成，则返回 true,
             * 注意：要先调用 shutdown();否则不会是 TRUE
             */
            if (exec.isTerminated()) {
                System.out.println("线程全部执行完成----Success");
                return Result.OK();
            }
        }
    }
}
